package cn.birdbaby.plugins.sync;

import com.google.common.collect.Maps;

import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;

/**
 * @author llorando 6/8/24 5:14 pm
 */
public final class SyncRegistry {
    private static Map<String, ? extends AbstractSyncer> annotator;

    private SyncRegistry() {
        //防止单例模式被破坏
        throw new UnsupportedOperationException();
    }

    static {
        //启动时加载，避免运行时才发现异常
        initProcessors();
    }

    public static Set<String> getSupportedAnnotations() {
        return annotator.keySet();
    }

    public static AbstractSyncer find(String annotationClassName) {
        if (annotator.get(annotationClassName) == null) {
            return annotator.get("default");
        }
        return annotator.get(annotationClassName);
    }

    public static void initProcessors() {
        Map<String, AbstractSyncer> map = Maps.newLinkedHashMap();
        ServiceLoader<AbstractSyncer> processors = ServiceLoader.load(AbstractSyncer.class, AbstractSyncer.class.getClassLoader());
        Iterator<AbstractSyncer> iterator = processors.iterator();

        while (iterator.hasNext()) {
            AbstractSyncer next = iterator.next();
            String annotationName = next.getSuffix();
            map.put(annotationName, next);
        }

        annotator = map;
    }
}
